import BaseAudioPlayer from "@/common/audio/BaseAudioPlayer";
import { MediaStatus } from "@/common/const";
// #ifdef H5
import Hls from "hls.js";
import type { Station } from "../types/interface";
// #endif

export default class H5AudioPlayer extends BaseAudioPlayer {
    private audioCtx = new Audio();
    private hls: Hls | null = null;

    constructor() {
        super();
        this.audioCtx.autoplay = true;
        this.audioCtx.loop = false;
        this.audioCtx.volume = 1;

        this.bindEvents();
    }

    private bindEvents() {
        this.audioCtx.addEventListener('play', () => this.setStatus(MediaStatus.play));
        this.audioCtx.addEventListener('pause', () => this.setStatus(MediaStatus.paused));
        this.audioCtx.addEventListener('ended', () => this.setStatus(MediaStatus.stoped));
        this.audioCtx.addEventListener('waiting', () => this.setStatus(MediaStatus.waiting));
        this.audioCtx.addEventListener('playing', () => this.setStatus(MediaStatus.playing));
        this.audioCtx.addEventListener('error', () => {
            this.setStatus(MediaStatus.error);
            // uni.showToast({ title: '播放失败', icon: 'none' });
        });
    }

    async play(radio: Station) {
        // const streamType = await checkAudioUrl(url);
        // if (streamType === 'm3u8') {
        if (radio?.hls) {
            if (Hls.isSupported()) {
                this.hls = new Hls();
                this.hls.attachMedia(this.audioCtx);
                this.hls.on(Hls.Events.MEDIA_ATTACHED, () => {
                    this.hls?.loadSource(radio.url);
                    this.hls?.on(Hls.Events.MANIFEST_PARSED, () => {
                        this.audioCtx.play();
                    });
                });
            }
        } else {
            this.audioCtx.src = radio.url;
            this.audioCtx.play().catch(() => this.setStatus(MediaStatus.error));
        }
    }

    pause() {
        this.audioCtx.pause();
        this.audioCtx.src = 'invalid';
        this.hls?.destroy(); // 同样释放 hls
        this.hls = null;
        this.setStatus(MediaStatus.paused);
    }

    stop() {
        this.audioCtx.pause();
        this.audioCtx.src = 'invalid';
        this.audioCtx.currentTime = 0;
        this.hls?.destroy(); // 释放 hls 实例
        this.hls = null;
        this.setStatus(MediaStatus.stoped);
    }
}
